package com.wanmait.wanmarecruit.interceptor;

import com.wanmait.wanmarecruit.entity.LoginLog;
import com.wanmait.wanmarecruit.entity.User;
import com.wanmait.wanmarecruit.service.LoginLogService;
import com.wanmait.wanmarecruit.service.UserService;
import com.wanmait.wanmarecruit.util.CookieUtils;
import com.wanmait.wanmarecruit.util.PasswordUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//验证cookie，七天免登录
@Component
public class WebCookieLogInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private LoginLogService loginLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
        if (user!=null)
        {
            return true;
        }
        String phone = CookieUtils.readCookie("phone",request);
        String pass = CookieUtils.readCookie("pass",request);
        if (phone==null||pass==null)
        {
            return true;
        }
        phone = phone.substring(2,phone.length()-2);
        User user1 = userService.getUserByPhone(phone);
        if (user1!=null)
        {
            if (PasswordUtils.checkPassword(user1.getPass(),pass))
            {
                request.getSession().setAttribute("user",user1);
                LoginLog loginLog = new LoginLog();
                loginLog.setUserId(user1.getId());
                loginLog.setIp(request.getRemoteAddr());
                loginLogService.save(loginLog);
            }
        }
        return true;
    }
}
